import {IPermissionTypes} from '@/types/permission.types'
import connection from '@/app/database'

class PermissionService {
  /**
   * 新增权限
   * @param permission 权限信息对象
   * @returns 
   */
  public create(permission: IPermissionTypes) {
    // 获取前端传入参数
    const {
      name,
      path,
      component,
      pid,
      type,
      icon,
      level,
      permissionValue
    } = permission

    const statement = `
            INSERT INTO permissions
            (name, path, component, pid, type, icon, level, permissionValue)
            VALUES
            (?, ?, ?, ?, ?, ?, ?, ?);`
    return connection.execute(
      statement,
      [
        name,
        path || null,
        component || null,
        pid,
        type,
        icon || null,
        level || 2,
        permissionValue || null
      ])
  }

  /**
   * 修改菜单权限
   * @param permission 
   * @returns 
   */
  public edit(permission: IPermissionTypes) {
    // 获取前端传入参数
    const {
      id,
      name,
      path,
      component,
      pid,
      type,
      icon,
      level,
      permissionValue
    } = permission

    const statement = `
        UPDATE permissions SET
          name = ?,
          path = ?,
          component = ?,
          pid = ?,
          type = ?,
          icon = ?,
          level = ?,
          permissionValue = ?
        WHERE id = ?;`
    return connection.execute(
      statement,
      [
        name,
        path || null,
        component || null,
        pid,
        type,
        icon || null,
        level,
        permissionValue || null,
        id
      ])
  }

  /**
   * 删除菜单权限
   * @param permissionId 权限id
   */
  public delete(permissionId: number) {
    const statement = `DELETE FROM permissions WHERE id = ? OR pid = ?;`
    return connection.execute(statement, [permissionId, permissionId])
  }

  /**
   * 根据权限名称 查询权限数据
   * @param pName 权限名称
   * @returns 权限数据
   */
  public getPermissionByName(pName: string, id: number) {
    let statement = `SELECT * FROM permissions WHERE name = ?;`
    // 如果携带id，需要排除自身name
    console.log(id)
    if (id > 0) {
      statement = `SELECT * FROM permissions WHERE name = ? And id != ?;`
    }
    return connection.execute(statement, [pName, id])
  }

  /**
   * 根据权限id 查询权限数据
   * @param id 权限id
   * @returns 权限数据
   */
  public getPermissionById(id: number) {
    const statement = `SELECT * FROM permissions WHERE id=?;`
    return connection.execute(statement, [id])
  }

  /**
   * 查询所有权限数据
   * @returns 权限数据
   */
  public getPermissions() {
    const statement = `SELECT * FROM permissions;`
    return connection.execute(statement)
  }
}

export default new PermissionService()